<template>
  <el-dialog
    title="分配权限"
    :visible="isShowDialog"
    @close="cancelFn"
  >
    <el-tree
      ref="allotTree"
      :data="permissions"
      show-checkbox
      node-key="id"
      default-expand-all
      :default-expanded-keys="[2, 3]"
      :default-checked-keys="permIds"
      :props="{label: 'name'}"
    />
    <div class="btn">
      <el-button @click="cancelFn">取消</el-button>
      <el-button
        type="primary"
        @click="allotFn"
      >确定</el-button>
    </div>

  </el-dialog>
</template>

<script>
import { listToTreeData } from '@/utils'
import { getPermissions } from '@/api/permission'
import { getRoleDetail, assignPrem } from '@/api/roles'
export default {
  data() {
    return {
      isShowDialog: false,
      permissions: null,
      permIds: [],
      roleId: ''
    }
  },
  async created() {
    // 获取所有的权限点
    const res = await getPermissions()
    this.permissions = await listToTreeData(res, '0')
  },
  methods: {
    async allotFn() {
      // !获取选中的权限点数据
      let permIds = await this.$refs.allotTree.getCheckedKeys()
      permIds = [...permIds, ...this.permIds]
      await assignPrem({ id: this.roleId, permIds })
      // 清空树形多选框的选中的数据
      this.$refs.allotTree.setCheckedKeys([])
      // 关闭弹窗
      this.isShowDialog = false
      this.$emit('update:getRoles')
    },
    // !关闭弹窗
    cancelFn() {
      // 树形控件清空默认选中数据还不行，还需要使用element中树形控件中的方法再次清空一次
      this.$refs.allotTree.setCheckedKeys([])
      this.isShowDialog = false
    },
    // !获取权限带你数据
    async getPermission(id) {
      this.permIds = []
      //   存放id
      this.roleId = id
      // 获取角色的权限点数据
      const { permIds } = await getRoleDetail(id)
      this.permIds = permIds
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-dialog .el-dialog__header {
  background-color: rgb(102, 177, 255);
  span {
    color: #fff;
  }
}
.btn {
  text-align: center;
}
</style>
